package com.westvalley.common.kit;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.Table;

public class StaticKit {
	static Map<Class<? extends Model<?>>,Map<String,Model<?>>> staticMap = new HashMap<Class<? extends Model<?>>, Map<String,Model<?>>>();
	
	@SuppressWarnings("unchecked")
	public static <T> T getModel(Class<? extends Model<?>> modelClass,String pk){
		if(Model.class.isAssignableFrom(modelClass)&& StringKit.notBlank(pk)){
			if(!staticMap.containsKey(modelClass))
				add(modelClass);
			return (T) staticMap.get(modelClass).get(pk);
		}
		return (T) ModelKit.newModel(modelClass);
	}
	
	static void add(Class<? extends Model<?>> modelClass){
		Table table = ModelKit.getTable(modelClass);
		if(table!=null){
			List<Record> recordList = Db.find("SELECT * FROM "+ table.getName());
			Map<String,Model<?>> map = new HashMap<String, Model<?>>();
			for(String pk : table.getPrimaryKey()){
				for(Record record : recordList){
					map.put(record.getStr(pk), ModelKit.toModel(modelClass, record));
				}
			}
			staticMap.put(modelClass, map);
		}
	}
}
